﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace _1.SchoolExercise.Model
{
    class StudentFactory
    {
        private static Dictionary<string, MutexFNPair> UniversitiesMutexAndFN;

        static StudentFactory()
        {
            UniversitiesMutexAndFN = new Dictionary<string, MutexFNPair>();
        }

        public static Student CreateStudent(string name, string university)
        {
            if (!UniversitiesMutexAndFN.ContainsKey(university))
            {
                lock (UniversitiesMutexAndFN)
                {
                    if (!UniversitiesMutexAndFN.ContainsKey(university))
                    {
                        UniversitiesMutexAndFN[university] = new MutexFNPair()
                        {
                            Mutex = new Student(university + " mutex", 9999),
                            FirstAvailableFN = 10000
                        };
                    }
                }
            }

            var uniMutex = UniversitiesMutexAndFN[university].Mutex;

            lock (uniMutex)
            { 
                int FN = UniversitiesMutexAndFN[university].FirstAvailableFN;
                Student newStudent = new Student(name, FN);
                UniversitiesMutexAndFN[university].FirstAvailableFN++;
                return newStudent;
            }
        }
        
    }

    internal class MutexFNPair
    {
        public Student Mutex;
        public int FirstAvailableFN;
    }
}
